import React, { createContext, useState } from 'react'
import classNames from 'classnames'
import { MenuItemProps } from './menuItem'

type menuMode = "horizontal" | "vertical"

type SelectCallback = (selectedIndex: string) => void;
export interface MenuProps {
    defaultIndex?: string,
    className?: string,
    mode?: menuMode,
    style?: React.CSSProperties,
    onSelect?: SelectCallback,
    defaultOpenSubMenus?: string[]
}
// 上下文 =====
export interface IMenContext {
    index?: string;
    onSelect?: SelectCallback;
    mode?: menuMode
}
export const MenuContext = createContext<IMenContext>({ index: '0' })
// ====
const Menu: React.FC<MenuProps> = (props) => {
    const { className, mode, style, children, defaultIndex, onSelect } = props
    // 第一个通用样式，第二个传进来的，第三个动态样式 
    const clsasses = classNames('viking-menu', className, {
        'menu-vertical': mode === 'vertical',
        'menu-horizontal': mode !== 'vertical'
    })
    // hooks 
    const [currentIdx, setCurrentIdx] = useState(defaultIndex)
    const handleClick = (index: string) => {
        setCurrentIdx(index)
        if (onSelect) {
            onSelect(index)
        }
    }

    // 创建上下文的值
    const passedContext: IMenContext = {
        index: currentIdx ? currentIdx : '0',
        onSelect: handleClick,
        mode
    }
    // 其它逻辑 
    //  渲染menuItem-并过滤掉不是这个类型的 
    const renderChildren = () => {
        // children===props.children child就是children上面的属性
        return React.Children.map(children, (child, index) => {
            const childrenElement = child as React.FunctionComponentElement<MenuItemProps>
            const { displayName } = childrenElement.type
            if (displayName === 'MenuItem' || displayName === 'SubMenu') {
                // return child
                return React.cloneElement(childrenElement, { index: index.toString() })
            } else {
                console.error('warn:menu has a child which is ');
            }
        })
    }


    return (
        <ul className={clsasses} style={style}>
            <MenuContext.Provider value={passedContext}>
                {/* {children} */}
                {renderChildren()}
            </MenuContext.Provider>
        </ul>
    )
}


export default Menu